{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31b91ffc",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "# 参数定义\n",
    "part1_defect_rate = [0.1, 0.2, 0.1, 0.2, 0.1, 0.05]\n",
    "part2_defect_rate = [0.1, 0.2, 0.1, 0.2, 0.2, 0.05]\n",
    "final_product_defect_rate = [0.1, 0.2, 0.1, 0.2, 0.1, 0.05]\n",
    "\n",
    "part1_cost = 4\n",
    "part2_cost = 18\n",
    "assemble_cost = 6\n",
    "detect_cost_part1 = [2, 2, 2, 1, 8, 2]\n",
    "detect_cost_part2 = [3, 3, 3, 1, 1, 3]\n",
    "detect_cost_final = [3, 3, 3, 2, 2, 3]\n",
    "market_price = 56\n",
    "replace_loss = [6, 6, 30, 30, 10, 10]\n",
    "decompose_cost = [5, 5, 5, 5, 5, 40]\n",
    "\n",
    "# 生产成品数量\n",
    "N = 100\n",
    "# 蒙特卡洛模拟次数\n",
    "simulations = 100\n",
    "\n",
    "# 计算多个成品的销量与利润\n",
    "def compute_total_sales_and_profit(d1, d2, d3, d4, N, situation):\n",
    "    defect_rate_part1 = part1_defect_rate[situation] if d1 == 0 else 0\n",
    "    defect_rate_part2 = part2_defect_rate[situation] if d2 == 0 else 0\n",
    "    basic_defect_rate = final_product_defect_rate[situation]\n",
    "    product_defect_rate = 1 - (1 - defect_rate_part1) * (1 - defect_rate_part2) * (1 - basic_defect_rate)\n",
    "    \n",
    "    # 计算合格产品数量与销售额\n",
    "    total_sales = N * (1 - product_defect_rate)\n",
    "    total_revenue = total_sales * market_price\n",
    "\n",
    "    # 计算成本\n",
    "    part1_total_cost = N * (part1_cost + (detect_cost_part1[situation] if d1 == 1 else 0))\n",
    "    part2_total_cost = N * (part2_cost + (detect_cost_part2[situation] if d2 == 1 else 0))\n",
    "    assembly_total_cost = N * (assemble_cost + (detect_cost_final[situation] if d3 == 1 else 0))\n",
    "    \n",
    "    # 如果未检测成品且次品，则产生调换损失\n",
    "    replacement_loss = N * product_defect_rate * replace_loss[situation] if d4 == 0 else 0\n",
    "    \n",
    "    # 拆解成本\n",
    "    decompose_total_cost = decompose_cost[situation] if d4 == 1 else 0\n",
    "\n",
    "    # 总成本\n",
    "    total_cost = part1_total_cost + part2_total_cost + assembly_total_cost + replacement_loss + decompose_total_cost\n",
    "    \n",
    "    # 总利润 = 总收入 - 总成本\n",
    "    total_profit = total_revenue - total_cost\n",
    "    \n",
    "    return total_sales, total_profit\n",
    "\n",
    "# 遗传算法的选择、交叉和变异操作\n",
    "def genetic_algorithm_optimization(simulations, generations=10, population_size=10, mutation_rate=0.1):\n",
    "    population = [(np.random.randint(0, 2), np.random.randint(0, 2), \n",
    "                   np.random.randint(0, 2), np.random.randint(0, 2)) for _ in range(population_size)]\n",
    "    \n",
    "    best_strategies = []\n",
    "    best_sales_per_generation = []\n",
    "    best_profit_per_generation = []\n",
    "    avg_profit_per_generation = []\n",
    "    \n",
    "    for generation in range(generations):\n",
    "        sales_for_population = []\n",
    "        total_profit_generation = []\n",
    "        \n",
    "        for strategy in population:\n",
    "            d1, d2, d3, d4 = strategy\n",
    "            total_sales_list = []\n",
    "            total_profit_list = []\n",
    "            for _ in range(simulations):\n",
    "                situation = np.random.randint(0, len(part1_defect_rate))\n",
    "                total_sales, total_profit = compute_total_sales_and_profit(d1, d2, d3, d4, N, situation)\n",
    "                total_sales_list.append(total_sales)\n",
    "                total_profit_list.append(total_profit)\n",
    "            avg_sales = np.mean(total_sales_list)\n",
    "            avg_profit = np.mean(total_profit_list)\n",
    "            sales_for_population.append((strategy, avg_sales, avg_profit))\n",
    "            total_profit_generation.append(avg_profit)\n",
    "        \n",
    "        best_strategy, best_sales, best_profit = max(sales_for_population, key=lambda x: x[2])\n",
    "        best_strategies.append(best_strategy)\n",
    "        best_sales_per_generation.append(best_sales)\n",
    "        best_profit_per_generation.append(best_profit)\n",
    "        avg_profit_per_generation.append(np.mean(total_profit_generation))\n",
    "        \n",
    "        sorted_population = sorted(sales_for_population, key=lambda x: x[2], reverse=True)\n",
    "        parent_population = [x[0] for x in sorted_population[:population_size // 2]]\n",
    "        \n",
    "        new_population = []\n",
    "        for _ in range(population_size // 2):\n",
    "            parent1_idx, parent2_idx = np.random.choice(len(parent_population), size=2, replace=False)\n",
    "            parent1 = parent_population[parent1_idx]\n",
    "            parent2 = parent_population[parent2_idx]\n",
    "            \n",
    "            crossover_point = np.random.randint(1, 4)\n",
    "            offspring1 = parent1[:crossover_point] + parent2[crossover_point:]\n",
    "            offspring2 = parent2[:crossover_point] + parent1[crossover_point:]\n",
    "            new_population.extend([offspring1, offspring2])\n",
    "        \n",
    "        for i in range(len(new_population)):\n",
    "            if np.random.rand() < mutation_rate:\n",
    "                mutation_idx = np.random.randint(0, 4)\n",
    "                new_population[i] = list(new_population[i])\n",
    "                new_population[i][mutation_idx] = 1 - new_population[i][mutation_idx]\n",
    "                new_population[i] = tuple(new_population[i])\n",
    "        \n",
    "        population = new_population\n",
    "\n",
    "    return best_strategies, best_sales_per_generation, best_profit_per_generation, avg_profit_per_generation\n",
    "\n",
    "# 定义生成结果的文件夹\n",
    "output_dir = \"output_generations\"\n",
    "if not os.path.exists(output_dir):\n",
    "    os.makedirs(output_dir)\n",
    "\n",
    "# 保存图表和结果的函数\n",
    "def save_results_and_plots(generations, best_sales_per_generation, avg_profit_per_generation, best_strategy_final, best_sales_final, best_profit_final, avg_profit_final):\n",
    "    # 保存每代最优期望销量图\n",
    "    plt.figure(figsize=(10, 6))\n",
    "    plt.plot(range(1, generations + 1), best_sales_per_generation, marker='o', linestyle='-', color='b', label='Best Sales')\n",
    "    plt.title(f'Best Expected Sales Over Generations (Generations={generations})')\n",
    "    plt.xlabel('Generation')\n",
    "    plt.ylabel('Best Expected Sales')\n",
    "    plt.grid(True)\n",
    "    best_sales_plot_file = os.path.join(output_dir, f'best_sales_{generations}.png')\n",
    "    plt.savefig(best_sales_plot_file)\n",
    "    plt.close()\n",
    "\n",
    "    # 保存每代平均期望利润图\n",
    "    plt.figure(figsize=(10, 6))\n",
    "    plt.plot(range(1, generations + 1), avg_profit_per_generation, marker='x', linestyle='--', color='g', label='Average Profit')\n",
    "    plt.title(f'Average Profit Over Generations (Generations={generations})')\n",
    "    plt.xlabel('Generation')\n",
    "    plt.ylabel('Average Profit (Yuan)')\n",
    "    plt.grid(True)\n",
    "    avg_profit_plot_file = os.path.join(output_dir, f'avg_profit_{generations}.png')\n",
    "    plt.savefig(avg_profit_plot_file)\n",
    "    plt.close()\n",
    "\n",
    "    # 保存文本结果\n",
    "    result_file = os.path.join(output_dir, f'result_{generations}.txt')\n",
    "    with open(result_file, 'w', encoding='utf-8') as f:\n",
    "        f.write(f\"Generations={generations}\\n\")\n",
    "        f.write(f\"最优策略: {best_strategy_final}\\n\")\n",
    "        f.write(f\"期望销量: {best_sales_final:.2f}\\n\")\n",
    "        f.write(f\"最佳利润: {best_profit_final:.2f} 元\\n\")\n",
    "        f.write(f\"平均利润: {avg_profit_final:.2f} 元\\n\")\n",
    "\n",
    "# 生成范围为100到500，每次间隔50的 generations\n",
    "generation_range = range(100, 501, 50)\n",
    "population_size = 10\n",
    "results = {}\n",
    "\n",
    "for generations in generation_range:\n",
    "    best_strategies, best_sales_per_generation, best_profit_per_generation, avg_profit_per_generation = genetic_algorithm_optimization(simulations, generations, population_size)\n",
    "\n",
    "    # 获取最终结果\n",
    "    best_strategy_final = best_strategies[-1]\n",
    "    best_sales_final = best_sales_per_generation[-1]\n",
    "    best_profit_final = best_profit_per_generation[-1]\n",
    "    avg_profit_final = avg_profit_per_generation[-1]\n",
    "\n",
    "    # 保存每次结果和图\n",
    "    save_results_and_plots(generations, best_sales_per_generation, avg_profit_per_generation, best_strategy_final, best_sales_final, best_profit_final, avg_profit_final)\n",
    "\n",
    "    # 保存结果到字典（如果需要进一步处理）\n",
    "    results[generations] = {\n",
    "        'best_strategy': best_strategy_final,\n",
    "        'best_sales': best_sales_final,\n",
    "        'best_profit': best_profit_final,\n",
    "        'avg_profit': avg_profit_final\n",
    "    }\n",
    "\n",
    "print(f\"All results and plots have been saved to the directory: {output_dir}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9d385a3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
